package com.ilikesoup.instant.enums.loader;

import com.ilikesoup.instant.enums.basic.SelectEnum;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 通过 key 查找到 SelectEnum，再通过 {@link SelectEnum#listGeneric} 方法生成下拉
 *
 * @author Soup
 */
public abstract class SelectEnumFinder implements SelectLoader {

    private final Map<String, Class<? extends Enum<?>>> classMapping = new ConcurrentReferenceHashMap<>();

    @Override
    public List<SelectEnum.SelectVo> load(String key) {
        return Optional.ofNullable(classMapping.computeIfAbsent(key, this::find))
                .map(SelectEnum::listGeneric).orElse(Collections.emptyList());
    }

    protected abstract Class<? extends Enum<?>> find(String key);

}
